﻿using Chain.BLL;
using Chain.Tasks;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;

public partial class AutoBackupDatabaseTask : ITask
{
    public void Execute(XmlNode node)
    {
        if (PubFunction.curParameter.AutoBackupDB)
        {
            Assembly.GetExecutingAssembly();
            string LuJing = AppDomain.CurrentDomain.BaseDirectory + @"AppData\AutoDataBase\";
            string[] FileNames = Directory.GetFiles(LuJing);
            if (FileNames.Length <= 0)
            {
                SysParameter par = new SysParameter();
                string databaseName = par.GetDataBaseName();
                string bakUpName = "Aoto" + databaseName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak";
                string fileName = LuJing + bakUpName;
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                    par.DataBakUp(fileName);
                }
                else
                {
                    par.DataBakUp(fileName);
                }
            }
            else
            {
                string LastFileName = FileNames[FileNames.Length - 1];
                DateTime LastFileTime = DateTime.ParseExact(LastFileName.Substring(LastFileName.Length - 0x12, 14).ToString(), "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
                int DD = PubFunction.curParameter.AutoBackupDay;
                DateTime AutoBackUpTime = LastFileTime.AddDays((double) DD);
                if ((DateTime.Now >= AutoBackUpTime) && Directory.Exists(LuJing))
                {
                    if (FileNames.Length > 2)
                    {
                        foreach (string item in FileNames)
                        {
                            if (File.Exists(item))
                            {
                                File.Delete(item);
                                break;
                            }
                        }
                    }
                    SysParameter par = new SysParameter();
                    string databaseName = par.GetDataBaseName();
                    string bakUpName = "Aoto" + databaseName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak";
                    string fileName = LuJing + bakUpName;
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                        par.DataBakUp(fileName);
                    }
                    else
                    {
                        par.DataBakUp(fileName);
                    }
                }
            }
        }
    }
}

